package edu.java.web;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;









import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.hamcrest.CoreMatchers;

import edu.java.ishop.model.UserRole;

public class AuthFilter implements Filter {

	
	private List<String> filteredPaths = Arrays.asList(new String[]{"product","add","remove","list","list.do"});
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		
		String requestURL = ((HttpServletRequest) req).getRequestURI();
		String path = StringUtils.substringAfterLast(requestURL, "/");
		

		
		if(!filteredPaths.contains(path)){
			chain.doFilter(req, resp);
			return;
		}
		UserRole currentUser = (UserRole)((HttpServletRequest) req).getSession().
				getAttribute("ISHOP_PRINCIPAL");
		
			if(currentUser != null){
				chain.doFilter(req, resp);
				return;
			}
		((HttpServletResponse) resp).sendRedirect("login.jsp?error=loginRequired");
		
		}
	

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
